package vn.appsmobi.activity;

 
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import vn.appsmobi.R;
import vn.appsmobi.service.AllMobileStoreWebService;
import vn.appsmobi.ulti.AlertHelper;
import vn.appsmobi.ulti.Constant;
import vn.appsmobi.ulti.Log;
import vn.appsmobi.ulti.Ulti;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.pm.Signature;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Base64;

public class SplashScreen extends Activity{
	static final int key_exit = 1;
	static final int time = 1000;
	Activity mActivity;
	StringBuilder resultVersion;
	AlertDialog.Builder alertbox; 
	AlertDialog alertDialog = null;
	 
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
//		// Add code to print out the key hash
//	    try {
//	        PackageInfo info = getPackageManager().getPackageInfo(
//	                "com.cdn.allmobilestore", 
//	                PackageManager.GET_SIGNATURES);
//	        for (Signature signature : info.signatures) {
//	            MessageDigest md = MessageDigest.getInstance("SHA");
//	            md.update(signature.toByteArray());
//	            Log.v("KeyHash:" + Base64.encodeToString(md.digest(), Base64.DEFAULT));
//	            }
//	    } catch (NameNotFoundException e) {
//
//	    } catch (NoSuchAlgorithmException e) {
//
//	    }
		
		setContentView(R.layout.activity_splashscreen);
		alertbox = new AlertDialog.Builder(this);
		alertbox.setTitle(getString(R.string.alert_nonetwork_title));
		alertbox.setMessage(getString(R.string.alert_nonetwork_content));
		alertbox.setCancelable(false);
		
		alertbox.setNegativeButton(R.string.Cancel,
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int arg1) {
						dialog.dismiss();
						finish();
					}
				});
		
		alertbox.setPositiveButton(R.string.OK,
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int arg1) {
						dialog.dismiss();
						startActivityForResult(new Intent(android.provider.Settings.ACTION_SETTINGS),1);							
					}
				}); 
		
		 
	}
	
	@Override
	protected void onStart() {
		super.onStart();
		Log.v( "Start");
		
		
		
	}
 
	@Override
	protected void onStop() {
		super.onStop();
		Log.v( "Stop");
		 
	}
	
	
	

	/* (non-Javadoc)
	 * @see android.app.Activity#onPause()
	 */
	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		
	}

	/* (non-Javadoc)
	 * @see android.app.Activity#onResume()
	 */
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		mActivity = this;
		Log.v("resume");
		if(!Ulti.isNetworkAvailable(this))
		{
			if(alertDialog == null)
				alertDialog = alertbox.show();
			else
				alertDialog.show();
			
		}
		else
		{	
			if(alertDialog != null)
			{
				alertDialog.hide();
			}
			handler.sendEmptyMessage(key_exit);
		}
	}




	Handler handler = new Handler(new Handler.Callback() {

		@Override
		public boolean handleMessage(Message msg) {
			if (msg.what == key_exit) {
				new CheckVersionTask().execute();
			}
			return false;
		}
	});

	private void openLoginActivity() {
		Intent intent = new Intent(this, MainTabActivity.class);
//		intent.putExtra(MainActivity.KEY_HAVE_ADVERTISEMENT, true);
		startActivity(intent);
		finish();
	}

	class CheckVersionTask extends AsyncTask<Void, Void, Integer> {
		ProgressDialog dialog;

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			resultVersion = new StringBuilder("");
			dialog = ProgressDialog.show(mActivity, "",
					mActivity.getString(R.string.text_loading), true, true,
					new DialogInterface.OnCancelListener() {
						@Override
						public void onCancel(DialogInterface dialog) {
							CheckVersionTask.this.cancel(true);
						}
					});
			dialog.setCanceledOnTouchOutside(false);
		}

		@Override
		protected Integer doInBackground(Void... params) {
			return AllMobileStoreWebService.checkVersion(mActivity,
					resultVersion);
		}

		@Override
		protected void onPostExecute(Integer result) {
			if(dialog != null)
				dialog.dismiss();
			
			Log.v("onPostExecute:" + result);
			switch (result) {
			case Constant.ERROR_NETWORK:
				AlertHelper.showMessageAlert(mActivity,
						getString(R.string.alert_nonetwork_title),
						getString(R.string.alert_nonetwork_content));
				break;
			case Constant.KEY_SUCCESS:
				showNotiVersion();
				break;
			case Constant.ERROR_REQUEST:
			default:
				AlertHelper.showMessageAlert(mActivity,
						getString(R.string.Error),
						getString(R.string.Error_orther));
				break;
			}
			super.onPostExecute(result);
		}
	}

	private void showNotiVersion() {
		if(resultVersion.length() > 0)
		{
			String result = resultVersion.substring(0, resultVersion.length());
			Log.v("resultVersion:" + resultVersion);
			if (result.equals(Constant.version_no_support)) {
				Log.v("resultVersion equal " + result);
				AlertHelper.showMessageAlertOKCancel(mActivity,
						mActivity.getString(R.string.text_noti_no_support),
						openPlayStoreLitener, cancelLitenerNoSupport);
						
				return;
			}

			if (result.equals(Constant.version_still_support)) {
				Log.v("still_support, show alert box");
				AlertHelper.showMessageAlertOKCancel(mActivity,
						mActivity.getString(R.string.text_noti_still_support),
						openPlayStoreLitener, cancelLitenerStillSupport);
						
				return;
			}

		}
		
	  	openLoginActivity();
	}

	DialogInterface.OnClickListener openPlayStoreLitener = new DialogInterface.OnClickListener() {

		@Override
		public void onClick(DialogInterface dialog, int which) {
			dialog.dismiss();
			PackageInfo pInfo;
			String packageName = "";
			try {
				pInfo = mActivity.getPackageManager().getPackageInfo(
						mActivity.getPackageName(), 0);
				packageName = pInfo.packageName;
			} catch (NameNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
					
			try {
								
				startActivity(new Intent(Intent.ACTION_VIEW,
						Uri.parse("market://detail?id="+packageName+"&auto="+ Constant.INTENT_EXTRA_NOTIFICATION_AUTO)));
				finish();
				
			} catch (android.content.ActivityNotFoundException anfe) {
				
			}
			mActivity.finish();
			
		}
	};

	DialogInterface.OnClickListener cancelLitenerNoSupport = new DialogInterface.OnClickListener() {

		@Override
		public void onClick(DialogInterface dialog, int which) {
			dialog.dismiss();
			mActivity.finish();
		}
	};

	DialogInterface.OnClickListener cancelLitenerStillSupport = new DialogInterface.OnClickListener() {

		@Override
		public void onClick(DialogInterface dialog, int which) {
			dialog.dismiss();
			openLoginActivity();
		}
	};
	
	 
}
